use bevy::prelude::*;

use super::{Player, PlayerExp};

///经验掉落物
#[derive(Component)]
pub struct ExpDrops;

pub fn monster_drops_exp(pos: Vec3, img: Handle<Image>) -> (SpriteBundle, ExpDrops) {
    (
        SpriteBundle {
            texture: img,
            transform: Transform {
                translation: pos.clone(),
                rotation: Quat::IDENTITY,
                scale: Vec3::ONE,
            },
            ..default()
        },
        ExpDrops,
    )
}

///经验的吸取和销毁
pub fn exp_move_or_destroyed(
    mut com: Commands,
    time: Res<Time>,
    mut palyer_exp: ResMut<PlayerExp>,
    mut exp_drops_q: Query<(Entity, &mut Transform), With<ExpDrops>>,
    palyer_q: Query<&mut Transform, (With<Player>, Without<ExpDrops>)>,
) {
    let palyer_pos = palyer_q.single();
    for (exp_drops_entity, mut exp_drops_transform) in exp_drops_q.iter_mut() {
        let distance = ((palyer_pos.translation.x - exp_drops_transform.translation.x).powi(2)
            + (palyer_pos.translation.y - exp_drops_transform.translation.y).powi(2))
        .sqrt();
        if distance <= 5. {
            palyer_exp.exp += 1;
            com.entity(exp_drops_entity).despawn();
        } else if distance <= 80. {
            let direction = palyer_pos.translation - exp_drops_transform.translation;
            let movement = direction.normalize_or_zero() * 200. * time.delta_seconds();
            exp_drops_transform.translation += movement;
        }
    }
}
